package com.mgface.eth.api;

import com.mgface.eth.tool.TxHashGetReceipt;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import java.math.BigInteger;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project web3jEthereum
 * @create 2018-06-25 17:55
 **/
public class SendTx {
	static final BigInteger GAS_PRICE = BigInteger.valueOf(22_000_000_000L);
	static final BigInteger GAS_LIMIT = BigInteger.valueOf(4_300_000);
	static final BigInteger value = Convert.toWei("1", Convert.Unit.ETHER).toBigInteger();
	static Admin web3j = Admin.build(new HttpService("https://ropsten.infura.io/IY77yuopq4bSgHoaFqJe"));
	public static void main(String[] args) throws Exception {
//		PersonalUnlockAccount personalUnlockAccount = web3j.personalUnlockAccount("0x2ee6e711da829ccfefe11d77c387c4888fc064cb","fc40dc0b755b243216b938956cd3fdd1a1f894a3a72a497a1feab01423ef0feb").send();
//		if (personalUnlockAccount.accountUnlocked()){
//			System.out.println("账户解锁成功！");
//		}
		//获取nonce
		EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
				"0x70982B82D6EdFDC91B0998c62954e703B7407747", DefaultBlockParameterName.LATEST).sendAsync().get();
		//
		BigInteger nonce = ethGetTransactionCount.getTransactionCount();
		System.out.println("当前交易的序列号:"+nonce);

		//String fileName  = WalletUtils.generateNewWalletFile("Xiang5326865+01",new File("D:\\project"),Boolean.TRUE);
		//System.out.println("生成的钱包私钥文件名:"+fileName);

		//Credentials credentials = WalletUtils.loadCredentials("Xiang5326865+01", "D:\\project\\"+fileName);
		Credentials credentials = Credentials.create("8341e5451480e81f220610f9ada693fe7a5dcc19d28833ce0c2f4f4d7f649104");
		RawTransaction rawTransaction  = RawTransaction.createEtherTransaction(
				nonce, GAS_PRICE, GAS_LIMIT, "0xc2A0966287031D489896B4d001723DE5fE45Ec51", value);

		byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
		String hexValue = Numeric.toHexString(signedMessage);
		EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();

		String transactionHash = ethSendTransaction.getTransactionHash();
		TransactionReceipt transactionReceipt = TxHashGetReceipt.passTxHashGetReceipt(transactionHash);
		System.out.println(transactionReceipt.getGasUsed());
	}

}
